package cn.rokhdelar.ams.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.rokhdelar.ams.common.domain.vo.PageVO;
import cn.rokhdelar.ams.management.domain.po.SysUser;
import cn.rokhdelar.ams.management.domain.po.SysUserRole;
import cn.rokhdelar.ams.management.domain.query.UserQuery;
import cn.rokhdelar.ams.management.domain.vo.RoleVO;
import cn.rokhdelar.ams.management.domain.vo.UserVO;
import cn.rokhdelar.ams.management.mapper.SysDepartmentMapper;
import cn.rokhdelar.ams.management.mapper.SysUserMapper;
import cn.rokhdelar.ams.management.service.SysUserRoleService;
import cn.rokhdelar.ams.management.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author rokhdelar
 * @since 2024-10-02 13:56:45
 * */
@Service
@RequiredArgsConstructor
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {

    private final PasswordEncoder passwordEncoder;
    private final SysUserRoleService sysUserRoleService;
    private final SysDepartmentMapper sysDepartmentMapper;

    @Override
    @Transactional
    public Boolean createUser(UserVO userVO) {
        //  判断用户名是否重复
        SysUser one = lambdaQuery().eq(SysUser::getName, userVO.getUsername()).one();
        if (one != null) {
            throw new RuntimeException("用户名已存在");
        }
        SysUser sysUser = BeanUtil.copyProperties(userVO, SysUser.class);
        sysUser.setPassword(passwordEncoder.encode(userVO.getCode()));
        if (save(sysUser)) {
            List<RoleVO> roleList = userVO.getRoleList();
            if (roleList != null && !roleList.isEmpty()) {
                //  插入新的角色信息
                for (RoleVO role : roleList) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRole.setRoleId(role.getId());
                    sysUserRoleService.save(sysUserRole);
                }
            }
        }
        return true;
    }

    /**
     * @param query 查询对象
     * @return 分页
     */
    @Override
    @Transactional
    public PageVO<UserVO> getUserListByPage(UserQuery query) {
        Page<SysUser> page = query.toPageDefaultSortByCreateTime();
        List<String> departmentIds = new ArrayList<>();
        //  获取本部门及子部门ID列表
        if (query.getDepartmentId() != null) {
            departmentIds = sysDepartmentMapper.getSubDepartmentIds(query.getDepartmentId());
        }

        Page<SysUser> userPage = lambdaQuery()
                .like(query.getName() != null, SysUser::getName, query.getName())
                .eq(query.getStatus() != null, SysUser::getStatus, query.getStatus())
                .in(!departmentIds.isEmpty(), SysUser::getDepartmentId, departmentIds)
                .page(page);

        return PageVO.of(userPage, UserVO.class);
    }

    /**
     * @param id 用户ID
     * @return UserVO对象
     */
    @Override
    @Transactional
    public UserVO getUserById(String id) {
        SysUser sysUser = getById(id);
        UserVO userVO = BeanUtil.copyProperties(sysUser, UserVO.class);
        userVO.setRoleList(baseMapper.getRoleListByUserId(id));
        return userVO;
    }

    /**
     * @param user UserVO对象
     * @return 是否成功
     */
    @Override
    @Transactional
    public Boolean updateUser(UserVO user) {
        //  更新用户基本信息
        saveOrUpdate(BeanUtil.copyProperties(user, SysUser.class));
        //  更新角色信息
        List<RoleVO> roleList = user.getRoleList();
        //  查询当前用户的所有角色
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, user.getId());
        //  删除原有角色
        sysUserRoleService.remove(wrapper);

        if (roleList != null && !roleList.isEmpty()) {
            //  插入新的角色信息
            for (RoleVO role : roleList) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getId());
                sysUserRole.setRoleId(role.getId());
                sysUserRoleService.save(sysUserRole);
            }
        }
        return true;
    }

    @Override
    public Boolean resetPassWord(UserVO user) {
        SysUser sysUser = getById(user.getId());
        sysUser.setPassword(passwordEncoder.encode("456456"));
        return updateById(sysUser);
    }

    /**
     * @param id 用户ID
     * @return 是否成功
     */
    @Override
    @Transactional
    public Boolean deleteUserById(String id) {
        //  删除角色信息
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id);
        sysUserRoleService.remove(wrapper);

        return removeById(id);
    }
}




